package com.yygo.dao.hibernate;

import com.yygo.dao.LoanProductDao;
import com.yygo.model.BondCompany;
import com.yygo.model.LoanProduct;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by tiansha on 2015/6/26.
 */
@Repository("loanProductDao")
public class LoanProductDaoHibernate extends GenericDaoHibernate<LoanProduct, Long> implements LoanProductDao {

    public LoanProductDaoHibernate() {
        super(LoanProduct.class);
    }

    @Override
    public LoanProduct loadLoanProduct(Long id) {
        LoanProduct loanProduct = get(id);
        Set<Long> ids = new HashSet<Long>();
        for (BondCompany bondCompany : loanProduct.getBonds()) {
            ids.add(bondCompany.getId());
        }
        loanProduct.setBondIds(ids);

        for (String name : loanProduct.getLoanMaterialNames()) {

        }
        for (String name : loanProduct.getCompleteLoanMaterialNames()) {

        }
        for (int name : loanProduct.getLoanYears()) {}

        return loanProduct;
    }

    public List<LoanProduct> getAll(boolean deleted) {
        Criteria criteria = getSession().createCriteria(LoanProduct.class).add(Restrictions.eq("deleted", deleted));
        return criteria.list();
    }

    @Override
    public Set<LoanProduct> getLoanProductsByBond(Long bondId, boolean isSecond) {
        Criteria criteria = getSession().createCriteria(BondCompany.class).add(Restrictions.eq("id", bondId));
        BondCompany bond = (BondCompany)criteria.uniqueResult();
        Set<LoanProduct> loanProducts = new HashSet<LoanProduct>();
        for (LoanProduct product : bond.getLoanProducts()) {
            if (product.isSecond() == isSecond) {
                loanProducts.add(product);
                for (String name : product.getLoanMaterialNames()) {

                }
                for (String name : product.getCompleteLoanMaterialNames()) {

                }
                for (int name : product.getLoanYears()) {}
            }
        }
        return loanProducts;
    }

    @Override
    public LoanProduct save(LoanProduct loanProduct) {
        if (loanProduct.getId() != null) {
            loanProduct = (LoanProduct)(getSession().merge(loanProduct));
        } else {
            getSession().saveOrUpdate(loanProduct);
            // necessary to throw a DataIntegrityViolation and catch it in UserManager
            getSession().flush();
        }
        return loanProduct;
    }
}
